package cmd

import (
	"fmt"
	"log"

	"github.com/gofiber/fiber/v2/middleware/cors"

	"github.com/cyfqyb/fiber_demo/config"
	"github.com/cyfqyb/fiber_demo/controller"
	"github.com/cyfqyb/fiber_demo/dao"
	"github.com/cyfqyb/fiber_demo/global"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/template/django/v3"
)

func Start() {
	engine := django.New("./frontend/views", ".html")
	app := fiber.New(fiber.Config{
		Views: engine,
	})
	app.Use(logger.New())
	app.Use(cors.New(cors.Config{
		// 允许所有来源的请求，实际生产中建议指定具体的域名
		AllowOrigins: "*",
		// 允许的 HTTP 方法
		AllowMethods: "*",
		// 允许的请求头
		AllowHeaders: "*",
	}))
	//配置静态文件
	app.Static("/static", "./frontend/static")
	//初始化viper, 用于读取配置文件
	config.InitViper()
	// 注册路由
	controller.InitController(app)
	//初始化所有配置
	config.InitConfigs(app)
	//初始化dao层
	dao.InitDao()
	port := global.Config.GetString("server.port")
	// 打印所有注册的路由
	printRegisteredRoutes(app)
	if err := app.Listen(fmt.Sprint(":" + port)); err != nil {
		log.Fatalf("服务器启动失败: %v", err)
	}
}

// printRegisteredRoutes 函数用于打印出 Fiber 应用中所有已注册的路由
func printRegisteredRoutes(app *fiber.App) {
	// 获取应用的所有路由信息
	routes := app.GetRoutes()

	fmt.Println("Registered Routes:")
	for _, route := range routes {
		// 打印每个路由的方法和路径
		fmt.Printf("Method: %s, Path: %s\n", route.Method, route.Path)
	}
}
